import React, { Component } from 'react'
import { TextareaItem, Modal, Toast } from 'antd-mobile'
import { NavBar, Image, Item, Icon, Button } from 'components'
import { hash } from 'muka'
import ImageCompressor from 'image-compressor.js'
import moment from 'moment'
import { post } from '../../../utils'

const ImageTypes: string[] = ['image/jpeg', 'image/jpg', 'image/png']

export default class CustomerServiceDetail extends Component<any, any> {

    public inputRef: any

    public state = {
        modalVis: false,
        multiple: false,
        applybtn: false,
        submitData: {
            reason: '',
            reasonDesc: '',
            address: '四川成都市武侯区天府大道东方希望天祥广场A座1117'
        },
        reason: [
            { title: '商品与页面描述不符' },
            { title: '商品损坏' },
            { title: '缺少件' },
            { title: '大小/颜色/型号等不适合' },
            { title: '发错货' },
            { title: '质量问题' },
        ],
        reasonClass: [],
        selectPhotoArr: []
    }
    public componentDidMount() {
        const { reason } = this.state
        let temp: any = []
        for (let i = 0; i < reason.length; i++) {
            if (i === 0) {
                temp[0] = 'barterDetail_reason_item barterDetail_reason_active'
            } else {
                temp[i] = 'barterDetail_reason_item barterDetail_reason_default'
            }
        }
        this.setState({
            reasonClass: temp,
        })
    }

    public render(): JSX.Element {
        const { modalVis, reason, reasonClass, submitData, selectPhotoArr } = this.state
        const { returnDetail } = this.props
        return (
            <div className="customerServiceDetail">
                <NavBar fixed={true} title={<div style={{ fontSize: '0.97rem', color: '#222' }}>换货</div>} />
                <div className="customerServiceDetail_goodsWrap">
                    <div className="customerServiceDetail_goodsWrap_goodsImg">
                        <Image src={returnDetail.pic} />
                    </div>
                    <div className="customerServiceDetail_goodsWrap_goodsInfo">
                        <div className="customerServiceDetail_goodsWrap_goodsTitle">
                            {returnDetail.short_title}
                        </div>
                        <div className="customerServiceDetail_goodsWrap_goodsSpec">
                            <div>单价：<span className="DINPro" style={{ color: '#222', fontSize: '0.8rem' }}>￥{returnDetail.price}+{returnDetail.price_q}</span></div>
                            <div>退货数量：<span className="DINPro" style={{ color: '#222', fontSize: '0.8rem' }}>{returnDetail.reNumber || returnDetail.number}</span></div>
                        </div>
                    </div>
                </div>
                <div style={{ padding: '0 0.4rem' }}>
                    {/* 原因 */}
                    <div className="customerServiceDetail_applyReason">
                        <Item
                            onPress={() => { this.setState({ modalVis: true }) }}
                            className="customerServiceDetail_applyReason_item"
                            title={
                                <span
                                    className="customerServiceDetail_applyReason_title"
                                >
                                    申请原因
                                </span>}
                            value={
                                <span
                                    className="customerServiceDetail_applyReason_icon"
                                >
                                    {(submitData.reason === '') ? '请选择申请原因' : submitData.reason}
                                    <Icon type="more" />
                                </span>}
                        />
                    </div>
                    {/* 问题描述 */}
                    <div className="customerServiceDetail_reasonDesc">
                        <div className="customerServiceDetail_reasonDesc_title">问题描述</div>
                        <div className="customerServiceDetail_reasonDesc_textarea">
                            <TextareaItem
                                value={submitData.reasonDesc}
                                onChange={this.handleInputText}
                                rows={3}
                                count={500}
                                className="customerServiceDetail_reasonDesc_textarea_item"
                                placeholder="请描述申请售后服务的具体原因，还可上传最多5张图片哦~"
                            />
                        </div>
                        <div className="customerServiceDetail_reasonDesc_selectImgWrap">
                            <div>
                                {
                                    selectPhotoArr.map((item: any, index: number) => {
                                        return (
                                            <div className="customerServiceDetail_reasonDesc_selectImgWrap_imgWrap" key={index}>
                                                <span onClick={this.handleRemovePhoto.bind(this, index)}><img src={require('../../../assets/error.png')} /></span>
                                                <img src={item.img} />
                                            </div>
                                        )
                                    })
                                }
                            </div>
                        </div>
                        <div className="customerServiceDetail_reasonDesc_photo">
                            <Icon type="camera" />
                            <div className="customerServiceDetail_reasonDesc_photo_select">
                                <input type="file" accept="image/*" ref={(ref) => { this.inputRef = ref }} onChange={this.handleSelectPhoto} />
                            </div>
                        </div>
                    </div>
                    {/* 退款方式 */}
                    <div className="customerServiceDetail_refunds">
                        <div>
                            <div>退款方式</div>
                            <div>什么是原方式返还?</div>
                        </div>
                        <div>
                            <span>原方式返回</span>
                        </div>
                    </div>
                    {/* 退货方式 */}
                    <div className="customerServiceDetail_returnWay">
                        <div>退货方式</div>
                        <div>
                            <span>快递至商家</span>
                        </div>
                        <div>商品寄回地址将在审核后以短信形式告知，或在申请记录中查询。</div>
                    </div>
                    {/* 联系方式 */}
                    <div className="customerServiceDetail_contact">
                        <div>
                            <Item className="customerServiceDetail_contact_item" title={<div className="customerServiceDetail_contact_title"><span>联系人</span><span>{returnDetail.user && returnDetail.user.name}</span></div>} />
                        </div>
                        <div>
                            <Item className="customerServiceDetail_contact_item" title={<div className="customerServiceDetail_contact_title">联系电话<span className="DINPro">{returnDetail.user && returnDetail.user.phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')}</span></div>} />
                        </div>
                    </div>
                    {/* 提示消息 */}
                    <div className="customerServiceDetail_noticeInfo">
                        提交服务单后，售后专员可能与您电话沟通，请保持手机畅通
                    </div>
                    <div className="customerServiceDetail_operation">
                        <div>
                            <Button className="customerServiceDetail_operation_btn" onClick={this.handleApply} disabled={(submitData.reason && submitData.reasonDesc) ? false : true}>提交申请</Button>
                        </div>
                    </div>
                </div>
                <Modal
                    popup={true}
                    visible={modalVis}
                    onClose={() => { this.setState({ modalVis: false }) }}
                    animationType="slide-up"
                >
                    <div className="customerServiceDetail_reason_content">
                        <div className="customerServiceDetail_reason_top">
                            <div>申请原因</div>
                            <div><Icon type="close" onClick={() => { this.setState({ modalVis: false }) }} /></div>
                        </div>
                        <div className="customerServiceDetail_reason_itemGroup">
                            {
                                reason.map((item: any, index: number) => {
                                    return (
                                        <div
                                            className={reasonClass[index]}
                                            key={index}
                                            onClick={() => { this.initReasonClass(index) }}
                                        >
                                            {item.title}
                                        </div>
                                    )
                                })
                            }
                        </div>
                    </div>
                </Modal>
            </div>
        )
    }

    private handleRemovePhoto = (i: number) => {
        let arr = [...this.state.selectPhotoArr]
        arr.splice(i, 1)
        this.setState({
            selectPhotoArr: arr
        })
    }

    private handleSelectPhoto = () => {
        const arr: any = [...this.state.selectPhotoArr]
        if (arr.length >= 5) {
            Toast.info('最多只能选择5张图片哦')
            return
        }
        const imgFile = this.inputRef.files[0]
        if (!imgFile) {
            return
        }
        if (!hash(ImageTypes, imgFile.type)) {
            Toast.info('只能上传图片文件哦')
            return
        }
        const imageCompressor = new ImageCompressor()
        imageCompressor.compress(imgFile, {
            quality: .6
        }).then((file: any) => {
            const fr = new FileReader()
            let obj: any = {}
            fr.onload = (result: any) => {
                if (result.target !== null) {
                    obj.img = result.target.result || ''
                    arr.push(obj)
                    this.setState({
                        selectPhotoArr: arr
                    })
                } else {
                    Toast.fail('图片读取失败！')
                }
            }
            fr.readAsDataURL(file)
        })
    }

    private handleApply = () => {
        const { userInfo } = this.props
        const { selectPhotoArr } = this.state
        const imgs = selectPhotoArr.map((item: any) => item.img)
        if (imgs.length) {
            post('indexapi/imgUpload', {
                userId: userInfo.id,
                typeImg: 'refundImg',
                file: imgs
            }).then((data: any) => {
                this.handleSend(data.join(','))
            })
        } else {
            this.handleSend()
        }
    }

    private handleSend(imgs?: string) {
        const { userInfo, returnDetail } = this.props
        const { submitData } = this.state
        post('orderapi/orderReturnGoodsSubmit', {
            userId: userInfo.id,
            order_id: returnDetail.order_id,
            order_goods_id: returnDetail.id,
            reason: submitData.reason,
            type: 2,
            notes: submitData.reasonDesc,
            pic: imgs,
            price: returnDetail.price,
            price_q: returnDetail.price_q
        }).then((val: any) => {
            this.props.history.push(`/My/customerServiceResult/${val}/${2}/${moment().format('YYYY-MM-DD')}`)
        })
    }
    private handleInputText = (val: string) => {
        const submitData = { ...this.state.submitData }
        submitData.reasonDesc = val
        this.setState({
            submitData,
        })
    }

    private initReasonClass = (index: number = 0) => {
        const { reason } = this.state
        const submitData = { ...this.state.submitData }
        let temp: any = []
        for (let i = 0; i < reason.length; i++) {
            if (i === index) {
                temp[index] = 'barterDetail_reason_item barterDetail_reason_active'
                submitData.reason = reason[index].title
            } else {
                temp[i] = 'barterDetail_reason_item barterDetail_reason_default'
            }
        }
        this.setState({
            reasonClass: temp,
            modalVis: false,
            submitData: submitData
        })
    }

    // private handleChangeImage = () => {
    //     console.log(1)
    //     let obj = {
    //         url: 'https://zos.alipayobjects.com/rmsportal/hqQWgTXdrlmVVYi.jpeg',
    //         id: '2122',
    //     }
    //     const data = cloneDeep(this.state.files)
    //     data.push(obj)
    //     this.setState({
    //         files: data
    //     })
    // }
}